import { reactive, ref } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app'

function handleListItem (item) {
	return item
}

export function useList(requestApi, queryObj = {}, handleListItem = handleListItem) {
	const queryList = {
		pageNumber: 1,
		pageSize: 10
	}
	const total = ref(0)
	const list = ref([])
	const loadMoreStatus = ref('loading')
		
	const getList = async() => {
		try{
			const _reqObj = {
				...queryList,
				...queryObj
			}
			const { data } = await requestApi(_reqObj)
			list.value.push(
				...data.records.map(handleListItem)
			)
			total.value = data.total
			if (list.value.length >= total.value) {
				loadMoreStatus.value = 'noMore'
			} else {
				loadMoreStatus.value = 'more'
				queryList.pageNumber++
			}
		}catch(e){
			console.log(e);
		}
	}
	
	const searchList = () => {
		loadMoreStatus.value = 'loading'
		queryList.pageNumber = 1
		getList()
	}
	
	onReachBottom(() => {
		if (loadMoreStatus.value === 'more') {
			loadMoreStatus.value = 'loading'
			getList()
		}
	})

	getList()

	return {
		list,
		total,
		searchList,
		loadMoreStatus
	}
}